# 获取存储过程中的所有表
import re
import os

from src.tool import FileTool

filePath = r"D:\test\txt"  # input() #文件夹路径
fileEncoding = "GBK"  # 文本编码格式


# 获取对应的表名称
def replaceText(file, TableName):
    file = file.replace("\n", "")
    rep = re.compile("(^\()*\(.*")  # 匹配从 ( 开始的所有字符串
    file = rep.sub("", file[file.index(TableName):])
    rep = re.compile("(^ )* .*")  # 匹配从 空行 开始的所有字符串
    var1 = rep.sub("", file[file.index(TableName):])
    return var1


# 文件处理过程
def fileProcess(fileName):
    list1 = []
    listDel = ["LBR.P_LBR_PROC_ETL_SETPARM", "LBR.P_LBR_PROC_ETL_JOBERROR"]
    with open(filePath + "/" + fileName, "r", encoding=fileEncoding) as fo:
        for file in fo:
            if "CREATE OR REPLACE PROCEDURE" in file:  # 不取第一行的存储过程名称,存储过程名称在最后添加
                continue
            if "LBR." in file:
                var1 = replaceText(file, "LBR.")
                list1.append(var1)
                continue
            if "VGR." in file:
                var1 = replaceText(file, "VGR.")
                list1.append(var1)
                continue
            if "RST." in file:
                var1 = replaceText(file, "RST.")
                list1.append(var1)
                continue
            if "目标表" in file:
                if "LBR" in file:
                    var1 = replaceText(file, "LBR")
                    listDel.append("LBR." + var1)
                    continue
                if "VGR" in file:
                    var1 = replaceText(file, "VGR")
                    listDel.append("VGR." + var1)
                    continue
                if "RST" in file:
                    var1 = replaceText(file, "RST")
                    listDel.append("RST." + var1)
                    continue
    list1 = list(set(list1))  # 去重
    for aa in listDel:
        list1.remove(aa)  # 去除非必要存储过程名称
    list1.sort()  # 排序
    list1.append(fileName)  # 追加存储过程名称在列表最后
    return list1  # 转换列表为字符串


# 引用文件夹下的文件
files = FileTool.FileTool(filePath).excelMain()

print(files)
# 判断生成的表名列表对应的文件夹是否存在
if not os.path.isdir(filePath + "/uu"):
    os.mkdir(filePath + "/uu")
with open(filePath + "/uu/文件名列表.txt", "w", encoding=fileEncoding) as fo1:
    for i in files:
        list1 = fileProcess(i)
        fo1.seek(0, 2)  # 设置追加到末尾
        fo1.write(' '.join(list1) + "\n")  # 转换列表为字符串并写入文件换行
